/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package model

import (
	"github.com/jinzhu/gorm"
	"time"
	"gitee.com/tugoer/psy-testing/code/env"
)

type Spoof struct {
	ID          int    `required:"ID 不能为空"`
	Author      int    `gorm:"index"`
	Data        string `required:"Data 不能为空"`
	Title       string `gorm:"index"`
	Kind        string `gorm:"index"`
	Logo        string
	Img         string
	Description string
	View        int        `gorm:"index"`
	Top         int        `gorm:"index"`
	LikeNum     int        `gorm:"index"`
	CreatedAt   *time.Time `gorm:"index"`
	UpdatedAt   *time.Time
}

func CountSpoof(author int) (total int, err error) {
	db := env.GormDB.Model(&Spoof{})
	if author > 0 {
		db = db.Where("author=?", author)
	}
	err = db.Count(&total).Error
	return
}

func SelectAuthorSpoof(author int, order string, limit, offset int) (ss []*Spoof, err error) {
	return SelectSpoof(func(db *gorm.DB) *gorm.DB {
		if author > 0 {
			db = db.Where("author=?", author)
		}
		return db.Order(order)
	}, limit, offset)
}

func SelectSpoof(where func(db *gorm.DB) *gorm.DB, limit, offset int) (ss []*Spoof, err error) {
	errs := where(env.GormDB).Limit(limit).Offset(offset).Find(&ss).GetErrors()
	for _, e := range errs {
		if e != nil && e != gorm.ErrRecordNotFound {
			return nil, e
		}
	}
	return
}

func (s *Spoof) Create(author int) error {
	s.Author = author
	return env.GormDB.Create(s).Error
}

func (s *Spoof) Update(author int) error {
	return env.GormDB.Model(Spoof{}).Where("id=? AND author=?", s.ID, author).Updates(s).Error
}

func (s *Spoof) Delete(author int) error {
	return env.GormDB.Where("id=? AND author=?", s.ID, author).Delete(s).Error
}
